"""
A model to read backup meta information from Datastore Admin tool.
"""
import datetime

from google.appengine.ext import ndb

class BackupInformation(ndb.Model):
    """
    An entity to keep information on backup operations.

    This is a wrapper for the built in BackupInformation found in google.appengine.ext.datastore_admin
    This should NOT be used to save an entity, ONLY READ-ONLY.
    """
    name = ndb.StringProperty()
    kinds = ndb.StringProperty(repeated=True)
    filesystem = ndb.StringProperty()
    start_time = ndb.DateTimeProperty(auto_now_add=True)
    active_jobs = ndb.StringProperty(repeated=True)
    completed_jobs = ndb.StringProperty(repeated=True)
    complete_time = ndb.DateTimeProperty(default=None)
    blob_files = ndb.StringProperty(repeated=True)
    original_app = ndb.StringProperty(default=None)
    gs_handle = ndb.TextProperty(default=None)

    @classmethod
    def _get_kind(cls):
        """
        override kind
        """
        return '_AE_Backup_Information'

    @classmethod
    def get_todays_backup_id(cls, bucket_name):
        """
        Lookups today backup and returns the id, otherwise None.

        NOTE: datstore_admin appends a random hash to the front of the backup files.  We want to parse this out
        and return just the ID.

        Example:
        ag5zfnJlcGNvcmUtcHJvZHJACxIcX0FF.Review.backup_info

        We will return ag5zfnJlcGNvcmUtcHJvZHJACxIcX0FF
        """
        entities = BackupInformation.query().order(-BackupInformation.complete_time)
        backup = None
        for entity in entities:
            # backup was stored to the big query bucket
            if entity.gs_handle and bucket_name in entity.gs_handle:
                backup = entity
                break
        if not backup or not backup.gs_handle:
            return None
        # backup was started today and has finished
        if backup.start_time.date() == datetime.datetime.utcnow().date() and backup.complete_time:
            return backup.gs_handle.split('/')[-1].replace('.backup_info', '')
        return None
